﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ruandao.MiniFace
{
    public class DetailsWidget : DetailsWidgetBase
    {
        /// <summary>
        /// 微件的属性：
        ///     1. DataObject：必须，是可以通过Python求值的表达式，如"ViewBag.Content"等等。
        ///     2. DataName: 可选，DataObject对象放到Python执行环境中所使用的变量名称，默认为DataObject。
        /// 微件的功能：用模板来呈现DataObject对象的详细内容。
        /// </summary>
        public DetailsWidget()
        {
        }

        protected override List<KeyValuePair<string, dynamic>> VariablesToPython(TemplateContext templateContext, out dynamic dataObject)
        {
            var list = new List<KeyValuePair<string, dynamic>>();
            dynamic widgetArgs = new System.Dynamic.ExpandoObject();

            string dataObjectArg;
            if (!Properties.TryGetValue("DataObject", out dataObjectArg))
            {
                throw new Exception("Details微件必须设置DataObject属性。");
            }
            widgetArgs.DataObject = dataObjectArg;

            string dataNameArg = "DataObject";
            if (Properties.ContainsKey("DataName")) dataNameArg = Properties["DataName"];
            widgetArgs.DataName = dataNameArg;

            list.Add(new KeyValuePair<string,dynamic>("WidgetArgs", widgetArgs));

            try
            {
                dataObject = templateContext.PythonScope.GetVariable(dataObjectArg);
            }
            catch (MissingMemberException except)
            {
                throw new Exception("无法获取Details微件中设置的dataobject为"+ dataObjectArg + "的对象。", except);
            }
            list.Add(new KeyValuePair<string,dynamic>(dataNameArg, dataObject));

            return list;
       }
    }
}
